package de.pharmacontrol.rfcserver.handler;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.logging.Logger;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import com.sap.conn.jco.AbapClassException;
import com.sap.conn.jco.AbapException;
import com.sap.conn.jco.JCoFunction;
import com.sap.conn.jco.server.JCoServerContext;

import de.pharmacontrol.pilot.entities.Order;
import de.pharmacontrol.psa.beans.interfaces.LoggerService;
import de.pharmacontrol.psa.beans.interfaces.OrderService;

@Stateless
public class DeleteOrderFunctionHandler extends FunctionHandler {

	@EJB
	LoggerService logger;

	@EJB
	OrderService orderBean;

	public final int DELETE_SUCCEEDED = 1;
	public final int DELETE_FAILED_NOT_EXIST = 2;
	public final int DELETE_FAILED_RUNNING = 3;

	/**
	 * <Z_PPFM_PCE_ORDER_DELETE> <INPUT> <I_HEADER>
	 * <ODERNR>000001001016</ODERNR> <ACTION>2</ACTION> </I_HEADER> </INPUT>
	 * <OUTPUT> <E_RETURNCODE></E_RETURNCODE> </OUTPUT>
	 * </Z_PPFM_PCE_ORDER_DELETE>
	 */
	@Override
	public void handleRequest(JCoServerContext serverCtx, JCoFunction function) throws AbapException, AbapClassException {

		final String xml = function.toXML();
		if (xml == null || xml.isEmpty()) {
			setReturnCode(function, NOT_DEFINED);
			return;
		}
		Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(this.getClass().getName() + " receives:" + xml);

		try {
			Order order = getParsedOrder(xml);
			if (order != null) {

				String orderName = order.getName();
				Order updatedOrder = orderBean.updateOrder(order);

				if (updatedOrder.getStatus() > 1) {
					logger.error(MessageFormat.format("Can not delete order:{0} with status: {1}", orderName, updatedOrder.getStatus()), null);
					setReturnCode(function, DELETE_FAILED_RUNNING);
					return;
				}

				if (orderBean.removeOrder(updatedOrder)) {
					logger.info(MessageFormat.format("Order:{0} deleted successfully", orderName));
					setReturnCode(function, DELETE_SUCCEEDED);
					return;
				}

			} else {
				setReturnCode(function, DELETE_FAILED_NOT_EXIST);
			}

		} catch (Exception e) {
			e.printStackTrace();
			setReturnCode(function, NOT_DEFINED);
		}

	}

	public Order getParsedOrder(String xml) throws XPathExpressionException, ParserConfigurationException, SAXException, IOException {
		DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();

		DocumentBuilder builder = domFactory.newDocumentBuilder();
		Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes()));

		XPath xpath = XPathFactory.newInstance().newXPath();
		String orderName = getNodeValue(xpath, doc, "Z_PPFM_PCE_ORDER_DELETE/INPUT/I_HEADER/ODERNR/text()");

		Order order = orderBean.findOrderByName(orderName);
		return order;
	}
}
